package com.sitc.street_lab_2013;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.sitc.street_lab_2013.entities.Answer;
import com.sitc.street_lab_2013.entities.Location;
import com.sitc.street_lab_2013.entityLogic.AnswerLogic;
import com.sitc.street_lab_2013.entityLogic.LocationLogic;

public class QuizActivity extends Activity {

	public final int SCAN_QR = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		populateDB();
		// automatically scan QR code
		Intent i = new Intent(QuizActivity.this, CameraPreview.class);
		// Set the request code to any code you like, you can identify
		// the
		// callback via this code
		startActivityForResult(i, SCAN_QR);
		

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.quiz, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == SCAN_QR) {
			if (data.hasExtra("qrcode")) {
				// parse the json retrieved from QR Code
				try {
					JSONObject jsonLocation = new JSONObject(data.getExtras()
							.getString("qrcode"));
					Iterator<?> keys = jsonLocation.keys();
					String key = (String) keys.next(); // only one key is stored
														// in our json object

					if (key.equalsIgnoreCase("locationId")) {
						final int locationId = jsonLocation.getInt(key);

						if (locationId == -1)// a very strange error occurred
												// (suppost already handled
												// during parsing)
						{
							Toast.makeText(getApplicationContext(),
									"No question exists!", Toast.LENGTH_SHORT)
									.show();
							startActivity(new Intent(getApplicationContext(),
									HomeListViewActivity.class));
						} else {
							// question can be answered multiple times

							setContentView(R.layout.activity_quiz);
							
							final LocationLogic locLogic = new LocationLogic(
									getApplicationContext());
							AnswerLogic ansLogic = new AnswerLogic(
									getApplicationContext());

							Location location = locLogic.getLocationById(
									locationId).get(0);
							ArrayList<Answer> answers = ansLogic
									.getAnswersByLocation(locationId);

							TextView txtQuestion = (TextView) findViewById(R.id.txtQuestion);
							ImageView imgQuestion = (ImageView)findViewById(R.id.imgQuestion);
							 
							Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
							RadioButton rb1 = (RadioButton) findViewById(R.id.radioBtn1);
							RadioButton rb2 = (RadioButton) findViewById(R.id.radioBtn2);
							RadioButton rb3 = (RadioButton) findViewById(R.id.radioBtn3);
							RadioButton rb4 = (RadioButton) findViewById(R.id.radioBtn4);
							final RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);

							this.setTitle(location.getLocationName());

							rb1.setText(answers.get(0).getAnsText());
							rb1.setTag(answers.get(0).isAnsIsCorrect());
							rb2.setText(answers.get(1).getAnsText());
							rb2.setTag(answers.get(1).isAnsIsCorrect());
							rb3.setText(answers.get(2).getAnsText());
							rb3.setTag(answers.get(2).isAnsIsCorrect());
							rb4.setText(answers.get(3).getAnsText());
							rb4.setTag(answers.get(3).isAnsIsCorrect());

							imgQuestion.setImageResource(this.getResources()
								.getIdentifier(
										location.getLocationImage().split(Pattern.quote("."))[0],
										"drawable",
										"com.sitc.street_lab_2013"));
//							txtQuestion
//									.setCompoundDrawablesWithIntrinsicBounds(
//											0,
//											this.getResources()
//													.getIdentifier(
//															location.getLocationImage().split(Pattern.quote("."))[0],
//															"drawable",
//															"com.sitc.street_lab_2013"),
//											0, 0);

							txtQuestion.setText(location.getLocationQuestion());

							btnSubmit.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									if (rg.getCheckedRadioButtonId() == -1) // no
																			// checked
																			// answer
									{
										Toast.makeText(getApplicationContext(),
												"Please choose an answer!",
												Toast.LENGTH_SHORT).show();
									} else {
										locLogic.updateLocation(locationId);// location
																			// is
																			// now
																			// answered

										// check total answered locations
										int totalAnswered = 0;
										ArrayList<Location> allLocs = (ArrayList<Location>) locLogic
												.getAllLocations();

										for (Location loc : allLocs) {
											totalAnswered = totalAnswered
													+ (loc.getLocationIsAnswered() ? 1
															: 0);
										}

										// if this was the last question
										if (totalAnswered == allLocs.size()) {
											// check if answer was correct
											if ((Boolean) rg
													.findViewById(
															rg.getCheckedRadioButtonId())
													.getTag() == true) { // if
																		// correct

												AlertDialog.Builder builder = new AlertDialog.Builder(
														QuizActivity.this);
												builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {					
													@Override
													public void onClick(DialogInterface dialog, int which) {
														startActivity(new Intent(
																QuizActivity.this,
																HomeListViewActivity.class));
													}
												});										
												
												TextView myMsg = new TextView(
														QuizActivity.this);
												myMsg.setTextSize(20);
												myMsg.setText("Great! Correct! You have now answered the last question! \n\nIf you want, you can go scan the questions again to try getting a better score or tell your friends to answer them! \n\nThanks for playing! Be sure to check out all points of interest on the map!");
												myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
												builder.setView(myMsg);
												builder.show();
											} else {
												AlertDialog.Builder builder = new AlertDialog.Builder(
														QuizActivity.this);
												builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {					
													@Override
													public void onClick(DialogInterface dialog, int which) {
														startActivity(new Intent(
																QuizActivity.this,
																HomeListViewActivity.class));
													}
												});		
												TextView myMsg = new TextView(
														QuizActivity.this);
												myMsg.setTextSize(20);
												myMsg.setText("Unlucky! You've chosen the wrong answer! \n\nDon't worry, you can scan this question or any other one again so that you can try to get a better score ! \n\nThanks for playing! Be sure to check out all points of interest on the map!");
												myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
												builder.setView(myMsg);
												builder.show();
											}
										} else {
											// check if answer was correct
											if ((Boolean) rg
													.findViewById(
															rg.getCheckedRadioButtonId())
													.getTag() == true) { // if
																		// correct

												Toast.makeText(
														getApplicationContext(),
														"Great! Correct! Go find the next question!",
														Toast.LENGTH_LONG)
														.show();
											} else {
												Toast.makeText(
														getApplicationContext(),
														"Incorrect! Scan the question again or go find the next question!",
														Toast.LENGTH_LONG)
														.show();
											}
										}
									}
								}
							});
						}

					}
				} catch (Exception e) {
					startActivity(new Intent(QuizActivity.this, HomeListViewActivity.class));
					Toast.makeText(getApplicationContext(),
							"This QR Code has no question!", Toast.LENGTH_LONG)
							.show();
					
				}

			}
		}
	}

	private void populateDB() {
		
		LocationLogic ll = new LocationLogic(getApplicationContext());
		AnswerLogic al = new AnswerLogic(getApplicationContext());


		List<Location> tempAllLocs = ll.getAllLocations();
		boolean isEmpty = tempAllLocs.size() == 0 ? true: false;
		
		if (!isEmpty) //TESTING PURPOSES
		{
			ll.deleteAllLocations();
			al.deleteAllAnswers();
		}	
		
		ll.createLocation(new Location(1, "What's your name?", "KATIDRAL", "q1.jpg", 1.1, 2.2, 0));
		al.createAnswer(new Answer(1, 1, "Colin", 1, ""));
		al.createAnswer(new Answer(2, 1, "Rambo", 0, ""));
		al.createAnswer(new Answer(3, 1, "Matthew is the best", 1, ""));
		al.createAnswer(new Answer(4, 1, "Joanna", 0, ""));
	}

}
